package com.dailyblue.example.project.bookstore.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dailyblue.example.project.bookstore.commons.bean.*;
import com.dailyblue.example.project.bookstore.user.service.AlipayService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class AlipayServiceImpl implements AlipayService {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @SneakyThrows
    public String alipay(String appId, String privateKey, String publicKey, String signType, String charset, String gatewayUrl, String notifyUrl, String returnUrl, Logistics logistics, String json) {
        // 获取到订单号 通过雪花算法
        long order_id = IdWorker.getId();
        List<FrontOrderItem> list = JSONArray.parseArray(json, FrontOrderItem.class);
        List<OrderItem> orderItems = new ArrayList<>();
        log.info("------------------------------------>");
        AtomicReference<Double> amount = new AtomicReference<>((double) 0);
        list.forEach(e -> {
            log.info("e:{}", e);
            // 计算总价
            amount.set(amount.get() + e.getPrice());
            // 获取订单详情
            OrderItem oi = new OrderItem();
            oi.setOrderId(order_id + "");
            oi.setNumber(e.getNumber());
            oi.setBookId(e.getBookId());
            orderItems.add(oi);
        });
        // 产生订单 生产
        Order order = new Order();
        order.setId(order_id + "");
        order.setUserId(list.get(0).getUserId());
        order.setTotalCount(list.size());
        order.setTotalAmount(amount.get());
        SendResult result1 = rocketMQTemplate.syncSend("ORDER1:ORDER", JSONArray.toJSONString(order));
        // 产生订单详情 生产
        SendResult result2 = rocketMQTemplate.syncSend("ORDER2:ORDER_ITEM", JSONArray.toJSONString(orderItems));
        // 产生物流信息 生产
        logistics.setOrderId(order_id + "");
        SendResult result3 = rocketMQTemplate.syncSend("ORDER3:LOGISTICS", JSONArray.toJSONString(logistics));
        if (result1.getSendStatus() == SendStatus.SEND_OK && result2.getSendStatus() == SendStatus.SEND_OK && result3.getSendStatus() == SendStatus.SEND_OK) {
            // 支付
            // 生成alipay客户端
            AlipayClient client
                    = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
            // 调用支付宝接口
            AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
            // 设置付款成功后应跳转的路径
            alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
            alipayTradeAppPayRequest.setReturnUrl(returnUrl);
            // 设置支付宝的各项参数
            Alipay alipay = new Alipay();
            alipay.setOut_trade_no(order_id + "");
            alipay.setTotal_amount(amount + "");
            alipay.setSubject(list.get(0).getUserId() + "的订单");
            alipay.setBody(list.get(0).getUserId() + "订单");
            String j = JSONArray.toJSONString(alipay);
            alipayTradeAppPayRequest.setBizContent(j);
            // 生成最终的订单
            return client.pageExecute(alipayTradeAppPayRequest).getBody();
        }
        return "error";
    }
}
